const WebSocket = require('ws');

// 创建WebSocket服务器
const wss = new WebSocket.Server({ port: 8080 });

// 存储连接的客户端
let clients = [];
let data = []
// 监听连接事件
wss.on('connection', (ws) => {
    console.log('Client connected');

    // 将新连接的客户端添加到数组中
    clients.push(ws);

    // 监听消息事件
    ws.on('message', (message) => {
        console.log('Received message:', message);
        data.push(JSON.parse(message))
        // 解析前端发送的JSON字符串为对象

        // 将收到的值广播给所有客户端
        clients.forEach((client) => {
            client.send(JSON.stringify(data));
        });
    });

    // 监听关闭事件
    ws.on('close', () => {
        console.log('Client disconnected');

        // 将断开连接的客户端从数组中移除
        clients = clients.filter((client) => client !== ws);
    });
});
